package Dao;

import Entity.Officer;
import Entity.Question;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class QuestionDao {
    //返回所有包含改关键词的问题
    public static List<Question> searchQuestions(String str) throws IOException {
        ObjectMapper om = new ObjectMapper();
        File file = new File("files\\Question.json");
        List<Question> list = new ArrayList<>();
        List<Question> questions = new ArrayList<>();
        if(file.exists() && file.length() != 0){
            list = om.readValue(file, new TypeReference<List<Question>>() {});
        }

        for(Question question:list){
            if(question.getContent().contains(str)||question.getOptions()[0].contains(str)||question.getOptions()[1].contains(str)||
                    question.getOptions()[2].contains(str)||String.valueOf(question.getNum()).contains(str)||question.getType()==str.charAt(0)){
                questions.add(question);
            }
        }
        return questions;
    }
    //返回所有的问题
    public static List<Question> getQuestions() throws IOException {
        ObjectMapper om = new ObjectMapper();
        File file = new File("files\\Question.json");
        List<Question> list = new ArrayList<>();
        if(file.exists() && file.length() != 0){
            list = om.readValue(file, new TypeReference<List<Question>>() {});
        }

        return list;
    }
    //用问题集合替换文件中的全部问题
    public static void changAll(List<Question> list) throws IOException {
        ObjectMapper om = new ObjectMapper();
        File file = new File("files\\Question.json");
        om.writeValue(file,list);
    }
    //添加问题
    public static void storeQuestion(Question question) throws IOException {
        File file = new File("files\\Question.json");
        ObjectMapper om = new ObjectMapper();
        List<Question> list = new ArrayList<>();
        if(file.exists() && file.length() != 0){
            list = om.readValue(file, new TypeReference<List<Question>>() {});
        }
        question.setNum(list.size()+1);
        list.add(question);
        om.writeValue(file,list);
    }
    //删除某问题
    public static void deleteQuestion(Question question) throws IOException {
        File file = new File("files\\Question.json");
        ObjectMapper om = new ObjectMapper();
        List<Question> list = new ArrayList<>();
        if(file.exists() && file.length() != 0){
            list = om.readValue(file, new TypeReference<List<Question>>() {});
        }

        boolean j=false;
        for(int i=0;i<list.size();i++){
            if(list.get(i).getContent().equals(question.getContent())){
                j=true;
                list.remove(i);
                i++;
            }
//            if(j) list.get(i).setNum(list.get(i).getNum()-1);
        }
        om.writeValue(file,list);
    }
}
